# -*- coding:utf8 -*-
import json
import traceback
import os
import re
import typing
from scrapy import Request, FormRequest
from squirrel_core.commons.utils.tools import calc_str_md5, upload_file
from squirrel_core.frame.spider_makaka import MakakaSpider

file_path = os.environ.get("FILE_PATH", "/")


class running8_score(MakakaSpider):
    name = "running8_score"
    serialNumber = ""
    specific_settings = {
        'URLLENGTH_LIMIT': 0
    }

    def get_ext_requests_or_urls(self, data=None):
        if data and isinstance(data, str):
            data = json.loads(data)
        if data and isinstance(data, typing.MutableMapping):
            self.serialNumber = data.get("serialNumber", "")
            race_id = data.get("spider_config", {}).get("race_id", "")
            user_id = data.get("spider_config", {}).get("user_id", "")
            race_no = data.get("spider_config", {}).get("race_no", "")
            user_name = data.get("spider_config", {}).get("user_name", "")
            race_name = data.get("spider_config", {}).get("race_name", "").replace(" ", "")
            home_url = data.get("spider_config", {}).get("url", "")
            card_num = data.get("spider_config", {}).get("card_num", "")
            if not home_url and not card_num:
                self.logger.info("url和card_num必须存在")
                self.upload_procedure({"serialNumber": self.serialNumber, "code": 101, "message": "url和card_num必须存在"})
                self.close_after_idle = True
                self.force_to_close_spider = True
            else:
                self.upload_procedure({"serialNumber": self.serialNumber, "code": 100, "message": "任务启动成功"})
                if "#小程序://智赛通" in home_url:
                    match_dict = {
                        "2025宝鸡马拉松": "101208"
                    }
                    match_id = match_dict.get(race_name, "")
                    url = f"https://api.zstong.com.cn/v3/matchGrades/oneGrades/{match_id}/{card_num}"
                    header = {
                        "Host": "api.zstong.com.cn",
                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090a13) UnifiedPCWindowsWechat(0xf2541022) XWEB/16467",
                        "Content-Type": "application/json",
                        "Accept": "*/*"
                    }
                    yield Request(url=url, callback=self.parse_zst, dont_filter=True, errback=self.err_parse, headers=header,
                                  meta={"race_id": race_id, "user_id": user_id, "card_num": card_num,
                                        "user_name": user_name, "race_name": race_name, "race_no": race_no})

                else:
                    yield Request(url=home_url, callback=self.parse, dont_filter=True, errback=self.err_parse,
                                  meta={"race_id": race_id, "user_id": user_id, "card_num": card_num,
                                        "user_name": user_name, "race_name": race_name, "race_no": race_no})

    def parse(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_no = response.meta.get("race_no", "")
        race_name = response.meta.get("race_name", "")
        user_name = response.meta.get("user_name", "")
        card_num = response.meta.get("card_num", "")
        try:
            self.logger.info(f"开始查找{race_no}的road_id:{response.url}")
            slug = "".join(re.findall(r"{slug:'(.*)?'", response.text)).strip()
            r_id = "".join(re.findall(r"race_id:(.*)?}", response.text)).strip()
            data = {"slug": slug, "id_card": card_num, "name": "", "phone": "", "bib": "", "race_id": int(r_id)}
            if race_name == "2025眉山东坡马拉松暨跑遍四川（东坡站）":
                data = {"slug": slug, "id_card": "", "name": "", "phone": "", "bib": race_no, "race_id": int(r_id)}
            url = "https://new-time.running8.com/query/score"
            header = {
                "Host": "new-time.running8.com",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
                "Content-Type": "application/json",
                "Accept": "*/*"
            }
            yield Request(url, callback=self.parse_score, errback=self.err_parse, method="POST",
                          body=json.dumps(data), dont_filter=True, headers=header,
                          meta={"race_id": race_id, "user_id": user_id,
                                "race_name": race_name, "user_name": user_name, "race_no": race_no})
        except Exception:
            self.logger.info(f"查找{race_no}的road_id时出错{response.url}：{traceback.format_exc()}")

    def parse_score(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_no = response.meta.get("race_no", "")
        race_name = response.meta.get("race_name", "")
        try:
            self.logger.info(f"开始解析{race_no}的基本成绩:{response.url}")
            data = json.loads(response.text).get("score", {})
            if data:
                score_data = {"race_name": race_name, "itemName": data.get("item", {}).get("title", ""), "index": "", "name": data.get("name", ""), "raceNo": data.get("bib", race_no),
                              "distance": data.get("item", {}).get("distance", 0) / 1000, "shotScore": data.get("total_score", ""), "score_status": "",
                              "score": data.get("net_score", ""), "sectionScore": [], "certImg": ""}
                cert_url = json.loads(response.text).get("certificate_img", "")
                if cert_url:
                    yield Request(url=cert_url, callback=self.parse_pic, errback=self.err_parse, dont_filter=True,
                                  meta={"race_id": race_id, "race_no": race_no, "user_id": user_id,
                                        "race_name": race_name, "score_data": score_data})
                else:
                    result = self.result_item_assembler(response)
                    result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                             "crawlerType": self.name_second, "data": str(score_data)}
                    yield result
            else:
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str({"msg": "未查到成绩"})}
                yield result
        except Exception:
            self.logger.info(f"查找{race_no}的基本成绩时出错{response.url}：{traceback.format_exc()}")

    def parse_zst(self, response, **kwargs):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_no = response.meta.get("race_no", "")
        race_name = response.meta.get("race_name", "")
        user_name = response.meta.get("user_name", "")
        try:
            self.logger.info(f"开始解析{user_name}的基本成绩")
            content = json.loads(response.text).get("data", {})
            if content:
                data = content.get("grades", {})
                score_data = {"race_name": race_name, "itemName": data.get("组别", ""), "index": data.get("净成绩排名", ""),
                              "name": data.get("姓名", user_name), "raceNo": data.get("参赛号", race_no),
                              "distance": "", "shotScore": data.get("枪声成绩", ""), "score_status": "",
                              "score": data.get("净成绩", ""), "sectionScore": [], "certImg": "", "speed": data.get("平均时速", "")}
                cert_url = content.get("cert", "")
                if cert_url:
                    yield Request(url=cert_url, callback=self.parse_pic, errback=self.err_parse, dont_filter=True,
                                  meta={"race_id": race_id, "race_no": race_no, "user_id": user_id,
                                        "race_name": race_name, "score_data": score_data})
                else:
                    result = self.result_item_assembler(response)
                    result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                             "crawlerType": self.name_second, "data": str(score_data)}
                    yield result
            else:
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str({"msg": "未查到成绩"})}
                yield result
        except Exception:
            self.logger.info(f"查找{user_name}的基本成绩时出错：{traceback.format_exc()}")

    def parse_pic(self, response):
        race_id = response.meta.get("race_id", "")
        user_id = response.meta.get("user_id", "")
        race_no = response.meta.get("race_no", "")
        score_data = response.meta.get("score_data", {})
        try:
            self.logger.info(f"开始下载{race_no}的证书：{response.url}")
            pic_md5 = calc_str_md5(response.url)
            pic_name = f"{race_no}_{pic_md5}.jpg"
            dir_path = os.path.join(file_path, "picture", self.name_first)
            if not os.path.exists(dir_path):
                os.makedirs(dir_path)
            save_path = os.path.join(dir_path, pic_name)
            if not os.path.exists(save_path):
                with open(save_path, "wb") as f:
                    f.write(response.body)
                upload_path = f"flow/{race_id}/{user_id}/pic/{pic_name}"
                upload_flag = upload_file(save_path, upload_path)
                if upload_flag:
                    self.logger.info(f"{save_path}上传成功：{upload_path}")
                else:
                    self.logger.info(f"{save_path}上传失败：{upload_path}")
                score_data["certImg"] = upload_path
                result = self.result_item_assembler(response)
                result['result_data'] = {"serialNumber": self.serialNumber, "webType": self.name_first,
                                         "crawlerType": self.name_second, "data": str(score_data)}
                yield result
        except Exception:
            self.logger.info(f"下载{race_no}证书时出错{response.url}：{traceback.format_exc()}")

    def err_parse(self, failure):
        self.logger.warning(f"请求失败：{failure.request.url},错误原因:{traceback.format_exc()}")

